import { useRequest, useSetState } from "ahooks";
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { getHttp, postHttp, deleteHttp, putHttp } from "../../../../api";
import style from "./style.module.scss";
import LeftArraw from "../../myConsultation/LeftArraw";
import { Custom } from "../../myConsultation/Custom";
import url1 from "../../../../assets/images/icon/common resource/hdpi/common_icon_attention_large_n.png";
import url2 from "../../../../assets/images/image/hdpi/gift_flower.png";
import url3 from "../../../../assets/images/image/hdpi/gift_certificate.png";
import url4 from "../../../../assets/images/image/hdpi/gift_cup.png";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import {
  addCommentList,
  addDoctorList,
} from "../../../../store/doctorDetail/doctorDetailSlice";
import { getTimeFormatText } from "../../../../utils/formatTime";
import love from "../../../../assets/images/icon/common resource/hdpi/common_icon_attention_large_s.png";
import { useAppSelector } from "../../../../store/hooks";
import { Notify } from "react-vant";

const Index: React.FC = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  // const userId = useAppSelector(state => state.user.userInfo.userId)
  // const sessionId = useAppSelector(state => state.user.userInfo.sessionId)
  // 跳转聊天
  const getCurrentInquiryRecord = () =>
    getHttp("/health/user/inquiry/verify/v1/findCurrentInquiryRecord", {
      userId,
      sessionId,
    });
  // 跳转聊天页
  const goChat = (doclist) => {
    const { doctorId, doctorName } = doclist;

    putHttp(
      `/health/user/inquiry/verify/v1/consultDoctor?doctorId=${doctorId}`
    ).then((res) => {
      if (res.status === "0000") {
        dispatch(addDoctorList(doctorId));
        getCurrentInquiryRecord().then((res) => {
          navigate(
            `/consultation/chat?doctorId=${doctorId}&doctorName=${doctorName}&recordId=${res.result.recordId}&imagePic=${res.result.imagePic}`
          );
        });
      } else {
        Notify.show({ message: res.message, type: "danger" });
      }
    });
  };
  // 跳转更多评论
  const goComments = () => {
    navigate("/consultation/comment/list");
    dispatch(addCommentList(commentList));
  };

  // 医生id
  const { doctorId } = useSelector((state: any) => state.doctor);
  // id类型
  const [infoDoctorId, setinfoDoctorId] = useSetState({
    doctorId: doctorId,
  });
  // id类型
  interface DoctorIdRawState {
    doctorId: number;
  }
  // console.log(doctorId, '1');

  // 医生详情接口
  const getDoctorId = (params: DoctorIdRawState) =>
    getHttp("/health/user/inquiry/v1/findDoctorInfo", params);
  const { data: doctorDetailList = [], run } = useRequest(async () => {
    const resp = await getDoctorId(infoDoctorId);
    return resp.result;
  });
  // console.log(doctorDetailList.doctorReceiveGiftList)
  const commentList = doctorDetailList.commentList;

  // 处理评论时间
  const timestampToTime = (timestamp) => {
    timestamp = timestamp ? timestamp : null;
    const date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    const Y = date.getFullYear() + "-";
    const M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "-";
    const D =
      (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
    const h =
      (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
    const m =
      (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
      ":";
    const s =
      date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    return Y + M + D + h + m + s;
  };

  // 用户id
  const userId = useAppSelector((state) => state.user.userInfo.userId);
  const sessionId = useAppSelector((state) => state.user.userInfo.sessionId);

  //关注医生
  const doctor_love = () =>
    postHttp("/health/user/inquiry/verify/v1/followDoctor", {
      userId: userId,
      sessionId: sessionId,
      doctorId: doctorId,
    });
  const doctor_noLove = () =>
    deleteHttp("/health/user/inquiry/verify/v1/cancelFollow", {
      userId: userId,
      sessionId: sessionId,
      doctorId: doctorId,
    });
  const doctor_s = () => {
    if (doctorDetailList.followFlag == 1) {
      Notify.show({ type: "danger", message: "取消关注" });
      doctor_noLove().then((resp) => {
        run();
      });
    } else {
      Notify.show({ type: "success", message: "关注成功" });
      doctor_love().then((resp) => {
        run();
      });
    }
  };

  return (
    <div>
      <LeftArraw title="医生详情"></LeftArraw>

      <div className={style["doctorDteail_top"]}>
        <div className={style["left-img"]}>
          <img src={doctorDetailList.imagePic} alt="" />
        </div>
        <div className={style["right-con"]}>
          <p>
            <span className={style["doctorName"]}>
              {doctorDetailList.doctorName}
            </span>{" "}
            <span className={style["doctorspan"]}>
              {doctorDetailList.jobTitle}
            </span>
            <img
              onClick={doctor_s}
              src={doctorDetailList.followFlag == 1 ? love : url1}
              alt=""
              className={style["doctorimg"]}
            />
          </p>
          <p>
            <span className={style["doctortwo"]}>
              {doctorDetailList.inauguralHospital}
            </span>
          </p>
          <p>
            <span className={style["doctorthree"]}>
              好评率&nbsp;{doctorDetailList.praise}
            </span>{" "}
            <span className={style["doctorthspan"]}>
              服务患者数
              <span className={style["doctor-item"]}>
                {doctorDetailList.serverNum}
              </span>
            </span>
          </p>
          <p className={style["gift"]}>他收到的礼物</p>
          <div className={style["userimg"]}>
            {doctorDetailList.doctorReceiveGiftList &&
            doctorDetailList.doctorReceiveGiftList.length == 0 ? (
              <div className={style["nogifts"]}>
                <div>
                  <img src={url2} alt="" /> <span>0</span>
                </div>
                <div>
                  <img src={url3} alt="" /> <span>0</span>
                </div>
                <div>
                  <img src={url4} alt="" /> <span>0</span>
                </div>
              </div>
            ) : (
              doctorDetailList.doctorReceiveGiftList &&
              doctorDetailList.doctorReceiveGiftList.map((v, i) => (
                <div key={i} className={style["ps"]}>
                  <img src={v.giftPic} alt="" />
                  <span>{v.worth}</span>
                </div>
              ))
            )}
          </div>
        </div>
      </div>
      <Custom title="个人简介"></Custom>
      <div className={style["personalProfile"]}>
        {doctorDetailList.personalProfile}
      </div>
      <div className={style["goodField_box"]}>
        <Custom title="擅长领域"></Custom>
        <div className={style["goodField"]}>{doctorDetailList.goodField}</div>
      </div>

      <div className={style["comment"]}>
        <Custom
          title={"用户评价" + `   (${doctorDetailList.commentNum}条评论)`}
        ></Custom>
        <div className={style["comment_list"]}>
          {commentList &&
            commentList.map((v, i) => (
              <div key={i} className={style["comment_div"]}>
                <p>
                  <img
                    src={v.headPic}
                    alt=""
                    className={style["comment_user_img"]}
                  />
                  <span>{v.nickName}</span>
                  <span>
                    {getTimeFormatText(
                      new Date(timestampToTime(v.commentTime))
                    )}
                  </span>
                </p>
                <p>{v.content}</p>
              </div>
            ))}
          <p className={style["more_comment"]} onClick={() => goComments()}>
            点击查看更多评论
          </p>
        </div>
      </div>

      <div className={style["price_gochat"]}>
        <div className={style["left"]}>
          {doctorDetailList.servicePrice}H币/次
        </div>
        <div className={style["right"]}>
          <button onClick={() => goChat(doctorDetailList)}>立即咨询</button>
        </div>
      </div>
    </div>
  );
};

export default Index;
